<?php
/**
 * 片区逻辑层
 */
namespace AuctionBack\Logic;
use AuctionBack\Model\RegionModel;
use AuctionCore\Other\Address;
use AuctionCore\Account\Back\Employee;
class RegionLogic{

    Protected $autoCheckFields = false;
    
    /**
     * 片区ID
     */
    private $rid;

    /**
     * 构造,初始化"片区ID"
     */
    public function __construct($rid)
    {
        $this->rid = $rid;
        $this->model = D("Region","Model");
    }

    /**
     * 新增
     */
    public static function create($data)
    {   
        M()->startTrans();
        $delInfo = D("Region","Model")->where(['leader'=>$data['leader']])->find();
        if ($delInfo) {
            $res = D("Region","Model")->where(['rid'=>$delInfo['rid']])->save(['leader'=>0]);
        }
        $res1 = M('region_maintain')->where(['maintain_id'=>$data['leader']])->delete();
        $data['createtime'] = date("Y-m-d H:i:s", time());
        $res2 = D("Region","Model")->add($data);
        if (!$res2) {
            M()->rollback();
            return false;
        }
        $info = [];
        $info['region_id'] = $res2;
        $info['maintain_id'] = $data['leader'];
        $info['createtime'] = date("Y-m-d H:i:s", time());
        $res3 = M('region_maintain')->add($info);
        if (!$res3) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $res2;
    }


    /**
     * 修改
     */
    public function update($data,$rid)
    {
        if ($rid < 1) return false;
        M()->startTrans();
        $regionInfo = $this->model->where(['rid' =>$rid])->find();
        if ($regionInfo['leader'] != $data['leader']) {
            $delInfo = $this->model->where(['leader'=>$data['leader']])->find();
            if ($delInfo) {
                $res1 = $this->model->where(['rid'=>$delInfo['rid']])->save(['leader'=>0]);
                if (!$res1) {
                    M()->rollback();
                    return false;
                }
            }
            $delInfo1 = M('region_maintain')->where(['maintain_id'=>$data['leader']])->find();
            if ($delInfo1) {
                $res2 = M('region_maintain')->where(['id'=>$delInfo1['id']])->delete();
                if (!$res2) {
                    M()->rollback();
                    return false;
                }
            }
            $beforeRegionMaintain = M('region_maintain')->where(['maintain_id'=>$regionInfo['leader']])->find();
            if ($beforeRegionMaintain) {
                $res3 = M('region_maintain')->where(['id'=>$beforeRegionMaintain['id']])->save(['maintain_id'=>$data['leader']]);
                if (!$res3) {
                    M()->rollback();
                    return false;
                }
            }else{
                $info = [];
                $info['region_id'] = $rid;
                $info['maintain_id'] = $data['leader'];
                $info['createtime'] = date("Y-m-d H:i:s", time());
                $res4 = M('region_maintain')->add($info);
                if (!$res4) {
                    M()->rollback();
                    return false;
                }
            }
        }
        $data['updatetime'] = date("Y-m-d H:i:s", time());
        $res = $this->model->where(['rid' =>$rid])->save($data);
        if (!$res) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $res;
    }

    /**
     * 片区名称检查
     */
    public function checkRegionName($regionName,$rid = 0)
    {   
        $map = [];
        if ($rid > 0) {
            $map['rid'] = ['neq',$rid];
        }
        $map['region_name'] = ['eq',$regionName];
        return $region = $this->model->where($map)->find();
    }

    /**
     * 片区信息
     */
    public function detail($rid)
    {
        return $regionInfo = $this->model->where(['rid' => $rid])->find();
    }


    /**
     * 片区详细信息
     */
    public function getRegionInfo($rid)
    {
        $regionInfo = [];
        $regionInfo = $this->model->where(['rid' => $rid])->find();
        if (empty($regionInfo)) return $regionInfo;
        $city = $regionInfo['city'];
        $regionInfo['branch_id'] = Address::get_branch_company_by_city_code($city);
        $empInfo = \AuctionCore\Account\Back\Employee::user_info_id($regionInfo['leader']);
        // dump($empInfo);
        $regionInfo['real_name'] = $empInfo['real_name'];
        $regionInfo['mobile'] = $empInfo['mobile'];
        $FourStore = D('FourStore','Logic');
        $regionInfo['fourStoreInfos'] = $FourStore->getInFourStoreByRid($rid);
        //片区评估师
        $regionInfo['appraisers'] = self::getRegionAppraiser($rid);
        if ($regionInfo['appraisers']) {
            foreach ($regionInfo['appraisers'] as $k => $v) {
                $regionInfo['appraisers'][$k]['count'] = $FourStore->getAppraiserFoursCount($v['emp_id']);
                $regionInfo['appraisers'][$k]['fourStore'] = $FourStore->getAppraiserFoursInfo($v['emp_id']);
            }
        }
        //片区维护人
        $regionInfo['maintains'] = self::getRegionMaintain($rid);
        if ($regionInfo['maintains']) {
            foreach ($regionInfo['maintains'] as $key => $value) {
                $regionInfo['maintains'][$key]['count'] = $FourStore->getFourStoreCount($value['emp_id']);
                $regionInfo['maintains'][$key]['fourStore'] = $FourStore->getFourStoreInfoByEmpId($value['emp_id']);
            }
        }
        return $regionInfo;
    }   

    /**
    * 列表
    */
    public static function getRegionList($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索 
        if (!empty($params['bc_city'])) {
             $map['city'] = array('in',$params['bc_city']);
        }
        if ($params['region_name']) {
            $map['region_name'] = array('eq',$params['region_name']);
        }
        if ($params['leader_phone']) {
            $empIds = Employee::getEmpIdByMobile($params['leader_phone']);
            $map['leader'] = array('in',$empIds);
        }
        if ($params['leader_contact']) {
            $mEmpIds = Employee::getEmpIdByName($params['leader_contact']);
            $map['leader'] = array('in',$mEmpIds);
        }
        $total = D('Region','Model')->where($map)->count();
        $list = D('Region','Model')->where($map)->limit($limit)->page($page)->order('rid desc')->select();
        foreach ($list as $key => $value) {
            $leaderInfo = Employee::user_info_id($value['leader']);
            $list[$key]['leader_name'] = $leaderInfo['real_name'];
            $list[$key]['leader_mobile'] = $leaderInfo['mobile'];
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    } 

    /**
    * 通过rid找片区名称
    */
    public function getRegionNameByRid($rid)
    {
        if ($rid < 1) return false;
        $region_name = D('Region','Model')->where(['rid' =>$rid])->getField('region_name');
        return $region_name;
    }

    /**
    * 关联4s店提交
    */
    public function regionRelationFourStorePost($rid,$fids)
    {   
        $FourStore = D('FourStore','Logic');
        $fourStoreInfos = $FourStore->getInFourStoreByRid($rid);
        $fourStoreIds = [];
        foreach ($fourStoreInfos as $key => $value) {
            $fourStoreIds[] = $value['fid'];
        }
        if(empty($fids)){
            if (empty($fourStoreIds)) return true; 
            $res = $FourStore->delRelationRegion($fourStoreIds);
            if (!$res) return false; 
        }else{
            $add_spm = array_diff($fids, $fourStoreIds);
            $del_spm = array_diff($fourStoreIds, $fids);
            if (!empty($add_spm)) {
                $res1 = $FourStore->addRelationRegion($add_spm,$rid);
                if (!$res1) return false; 
            }
            if (!empty($del_spm)) {
                $res2 = $FourStore->delRelationRegion($del_spm);
                if (!$res2) return false; 
            }
        }
        return true;
    }


    /**
    * 片区关联维护人提交
    */
    public function regionRelationMaintainPost($rid,$postMaintainIds)
    {   
        $regionMaintain = M('region_maintain')->where(['region_id'=>$rid])->select();
        $maintainIds = [];
        foreach ($regionMaintain as $key => $value) {
            $maintainIds[] = $value['maintain_id'];
        }
        if(empty($postMaintainIds)){
            if (empty($maintainIds)) return true; 
            foreach ($maintainIds as $k => $val) {
                $res = $this->delRelationMaintain($val);
                if (!$res) return false; 
            }
        }else{
            $add_spm = array_diff($postMaintainIds, $maintainIds);
            $del_spm = array_diff($maintainIds, $postMaintainIds);
            if (!empty($add_spm)) {
                foreach ($add_spm as $k1 => $v1) {
                    $res1 = $this->addRelationMaintain(['region_id'=>$rid,'maintain_id'=>$v1]);
                    if (!$res1) return false; 
                }
            }
            if (!empty($del_spm)) {
                foreach ($del_spm as $k2 => $v2) {
                    $res2 = $this->delRelationMaintain($v2);
                    if (!$res2) return false; 
                } 
            }
        }
        return true;
    }

    /**
    * 解除片区与维护人关系
    */
    public function delRelationMaintain($maintainId)
    {
        if($maintainId < 1) return false;
        $map = [];
        $map['maintain_id'] = ['eq',$maintainId];
        $res = M('region_maintain')->where($map)->delete();
        return $res;
    }
    /**
    * 绑定片区与维护人关系
    */
    public function addRelationMaintain($data) 
    {
        $data['createtime'] = date("Y-m-d H:i:s", time());
        $res = M('region_maintain')->add($data);
        return $res;
    }

    /**
    *找到维护人关联片区数量
    */
    public static function getRegionCount($emp_id)
    {   
        $count = M('region_maintain')->where(['maintain_id'=>$emp_id])->count();
        return $count;
    }

    /**
    *找到片区下的维护人
    */
    public static function getRegionMaintain($rid)
    {   
        $prefix = C('DB_PREFIX');
        $maintain = M('region_maintain')->alias("rm")->field("e.emp_id,e.real_name")
                ->join("{$prefix}employee e ON e.emp_id = rm.maintain_id")
                ->where(['rm.region_id'=>$rid])->select();
        return $maintain;
    }

    /**
    *找到片区下的评估师
    */
    public static function getRegionAppraiser($rid){
        $prefix = C('DB_PREFIX');
        $appraiser = M('fours')->alias("f")->field("e.emp_id,e.real_name")
                ->join("{$prefix}fours_appraiser fa ON f.fid = fa.f_id")
                ->join("{$prefix}employee e ON e.emp_id = fa.appraiser_id")
                ->where(['f.region_id'=>$rid])->group('e.emp_id')->select();
        return $appraiser;
    }

    /**
    *找到城市下的片区
    */
    public function getRegionByCity($city){
        $map = array();
        $region = D('Region','Model') ->field('rid,region_name')->where(['city' =>$city])->select();
        return $region;
    }

    /**
    *找到城市下的片区
    */
    public function getRegionByLeader($leader){
        $region = D('Region','Model') ->field('rid,region_name')->where(['leader' =>$leader])->find();
        return $region;
    }

}